#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MaxSize 6
#define ElemType int
/**
 *@param int front 队首元素地址
 *@param int rear 队尾元素下一个位置地址
 */
typedef struct
{
    ElemType data[MaxSize];
    int front, rear;
    // int tag = 0;//记录前一次操作是删除还是插入，删除赋值0，插入赋值1，以此不浪费一个空间，实现判断队列是否为满
} SqQueue;

void init(SqQueue *);
bool is_empty(SqQueue *);
bool is_full(SqQueue *);
void enter(SqQueue *, ElemType);    // 进队
void traverse(SqQueue *);           // 遍历队列输出
bool delete(SqQueue *, ElemType *); // 出队
void clear(SqQueue *);              // 清空队列
int count(SqQueue *);               // 计算队列元素个数

int main()
{
    SqQueue Q;
    ElemType val;
    init(&Q);
    enter(&Q, 5);
    enter(&Q, 6);
    enter(&Q, 3);
    enter(&Q, 9);
    enter(&Q, 4);
    enter(&Q, 10);
    enter(&Q, 2);
    enter(&Q, 0);
    traverse(&Q);
    if (delete (&Q, &val))
    {
        printf("Deleted!Element is %d.\n", val);
    }
    else
    {
        printf("Failed to delete!Queue is empty!\n");
    }
    enter(&Q, 10);
    enter(&Q, 2);
    printf("The number of elements in the queue is %d.\n", count(&Q));
    traverse(&Q);
    clear(&Q);
    traverse(&Q);
    return 0;
}

void init(SqQueue *pQ)
{
    pQ->front = 0;
    pQ->rear = pQ->front;
    return;
}
bool is_empty(SqQueue *pQ)
{
    if (pQ->front == pQ->rear)
        return true;
    else
        return false;
}
bool is_full(SqQueue *pQ)
{
    if ((pQ->rear + 1) % MaxSize == pQ->front)
        return true;
    else
        return false;
}
void enter(SqQueue *pQ, ElemType val) // 入队
{
    if (is_full(pQ))
    {
        printf("Failed to enter!Queue is full!\n");
        return;
    }
    pQ->data[pQ->rear] = val;
    pQ->rear = (pQ->rear + 1) % MaxSize;
    printf("Entered successfully!\n");
    return;
}
void traverse(SqQueue *pQ) // 遍历队列输出
{
    if (is_empty(pQ))
    {
        printf("Failed to traverse!Queue is empty!\n");
        return;
    }
    int temp = pQ->front;
    while (temp != pQ->rear)
    {
        printf("%d ", pQ->data[temp]);
        temp = (temp + 1) % MaxSize;
    }
    printf("\nTraversed successfully!\n");
    return;
}
bool delete(SqQueue *pQ, ElemType *pVal) // 出队
{
    if (is_empty(pQ))
    {
        return false;
    }
    *pVal = pQ->data[pQ->front];
    pQ->front = (pQ->front + 1) % MaxSize;
    return true;
}
void clear(SqQueue *pQ)
{
    pQ->rear = pQ->front;
    printf("Cleared successfully!\n");
    return;
}
int count(SqQueue *pQ)
{
    return (pQ->rear - pQ->front + MaxSize) % MaxSize;
}